package com.pianzhu.blockchainemr.controller;

import com.pianzhu.blockchainemr.pojo.*;
import com.pianzhu.blockchainemr.pojo.Param.ChangeVisitStatusParam;
import com.pianzhu.blockchainemr.pojo.Param.EmpowerParam;
import com.pianzhu.blockchainemr.pojo.result.*;
import com.pianzhu.blockchainemr.service.DoctorService;
import com.pianzhu.blockchainemr.utils.AliyunOSSOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/doctor")
public class DoctorController {

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /**
     * 获取我的患者列表（分页）
     * @param doctorId 医生ID
     * @param pageNum 页码，默认1
     * @param pageSize 每页大小，默认10
     * @param patientName 患者姓名搜索（可选）
     * @param visitId 就诊ID搜索（可选）
     */
    @GetMapping("/myPatients")
    public Result getMyPatients(
            @RequestParam("doctorId") Long doctorId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String patientName,
            @RequestParam(required = false) String visitId) {

        PageResult<PatientResult> pageResult = doctorService.getMyPatients(
                doctorId, pageNum, pageSize, patientName, visitId
        );
        return Result.success(pageResult);
    }

    @GetMapping("/myPatients/count")
    public Result getMyPatientsCount(@RequestParam("doctorId") Long doctorId) {
        Long count = doctorService.getMyPatientsCount(doctorId);
        return Result.success(count);
    }


    @PostMapping("/changeVisitStatus")
    public Result changeVisitStatus(@RequestBody ChangeVisitStatusParam param) {
        doctorService.changeVisitStatus(param);
        return Result.success();
    }

    @GetMapping("/getMedicalRecord")
    public Result getMedicalRecord( @RequestHeader("visitId") String visitId,
                                    @RequestHeader("doctorId") Integer doctorId) {
        List<MedicalRecordListResult> medicalRecordInfos = doctorService.getMedicalRecord(visitId,doctorId);
        return Result.success(medicalRecordInfos);
    }

    @PostMapping("/requestEmpower")
    public Result requestEmpower(@RequestBody EmpowerParam empowerParam) {
        doctorService.requestEmpower(empowerParam);
        return Result.success();
    }

    @GetMapping("/getChiefComplaint")
    public Result getChiefComplaint(@RequestHeader("visitId") String visitId) {
        String chiefComplaint = doctorService.getChiefComplaint(visitId);
        return Result.success(chiefComplaint);
    }

    @GetMapping("/getMedicalReport")
    public Result getMedicalReport(@RequestHeader("visitId") String visitId,
                                   @RequestHeader("doctorId") Integer doctorId) {
        List<MedicalReportListResult> medicalReportInfos = doctorService.getMedicalReport(visitId,doctorId);
        return Result.success(medicalReportInfos);
    }

    @PostMapping("requestMedicalReportEmpower")
    public Result requestMedicalReportEmpower(@RequestBody EmpowerParam empowerParam) {
        doctorService.requestMedicalReportEmpower(empowerParam);
        return Result.success();
    }

    /**
     * 搜索患者接口
     * @param keyword 搜索关键词（患者姓名或诊疗号）
     * @param doctorId 医生ID
     * @return 搜索结果列表
     */
    @GetMapping("/searchPatients")
    public Result searchPatients(@RequestParam("keyword") String keyword,
                                 @RequestParam("doctorId") Long doctorId) {
        try {
            List<PatientResult> patientResults = doctorService.searchPatients(doctorId, keyword);
            return Result.success(patientResults);
        } catch (Exception e) {
            return Result.error("搜索患者失败");
        }
    }

    @PostMapping("/newMedicalRecord")
    public Result newMedicalRecord(@RequestBody EmrDocuments emrDocuments){
        try {
            doctorService.newMedicalRecord(emrDocuments);
            return Result.success();
        } catch (Exception e) {
            return Result.error("创建病历失败: " + e.getMessage());
        }
    }

    /**
     * 新建检查检验报告接口
     * @param emrExamReports 检查检验报告数据
     * @return 创建结果
     */
    @PostMapping("/newMedicalReport")
    public Result newMedicalReport(@RequestBody EmrExamReports emrExamReports) {
            doctorService.newMedicalReport(emrExamReports);
            return Result.success("报告创建成功");
    }

    /**
     * 上传文件到OSS接口
     * @param file 上传的文件
     * @return OSS文件URL
     */
    @PostMapping("/newOssFile")
    public Result newOssFile(@RequestParam("file") MultipartFile file) {
        try {
            // 检查文件大小（不超过50MB）
            if (file.getSize() > 50 * 1024 * 1024) {
                return Result.error("文件大小不能超过50MB");
            }
            
            // 检查文件类型（支持图片和PDF格式）
            String contentType = file.getContentType();
            if (!(contentType != null && (contentType.startsWith("image/") || contentType.equals("application/pdf")))) {
                return Result.error("只支持图片和PDF格式的文件");
            }
            
            // 上传文件到OSS
            String ossUrl = aliyunOSSOperator.upload(file.getBytes(), file.getOriginalFilename());
            return Result.success(ossUrl);
        } catch (Exception e) {
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/getItemList")
    public Result getItemList() {
        List<EmrExamItemDict> itemResults = doctorService.getItemList();
        return Result.success(itemResults);
    }

    @GetMapping("/getPrescriptionList")
    public Result getPrescriptionList(@RequestHeader("patientId") String patientId) {
        List<EmrMedOrders> prescriptionResults = doctorService.getPrescriptionList(patientId);
        return Result.success(prescriptionResults);
    }
    @GetMapping("/getPatientInfo")
    public Result getPatientInfo(@RequestHeader("patientId") String patientId) {
        EmrPatMaster patientInfoResult = doctorService.getPatientInfo(patientId);
        return Result.success(patientInfoResult);
    }

    @PostMapping("/createPrescription")
    public Result createPrescription(@RequestBody EmrMedOrders emrMedOrders) {
        doctorService.createPrescription(emrMedOrders);
        return Result.success();
    }

    @GetMapping("/getDrugList")
    public Result getDrugList() {
        List<EmrDrugDict> drugDicts = doctorService.getDrugList();
        return Result.success(drugDicts);
    }

    @GetMapping("/getVisitList")
    public Result getVisitList(@RequestHeader("patientId") String patientId,@RequestHeader("doctorId") Integer doctorId) {
        List<EmrMedVisit> visitList = doctorService.getVisitList(patientId,doctorId);
        return Result.success(visitList);
    }

    @GetMapping("/getMyPrescriptionList")
    public Result getMyPrescriptionList(@RequestHeader("doctorId") String doctorId) {
        List<EmrMedOrders> prescriptionResults = doctorService.getMyPrescriptionList(doctorId);
        return Result.success(prescriptionResults);
    }

    @PostMapping("/deletePrescription")
    public Result deletePrescription(@RequestBody EmrMedOrders emrMedOrders) {
        doctorService.deletePrescription(emrMedOrders);
        return Result.success();
    }

    /*
    * {
  "orderId": 1,
  "frequency": "每日三次",
  "startTime": "2024-01-20 10:00:00",
  "endTime": "2024-01-27 10:00:00",  // 仅药品处方需要
  "orderStatus": "verified"
}
    * */
    @PostMapping("/updatePrescription")
    public Result updatePrescription(@RequestBody EmrMedOrders emrMedOrders) {
        doctorService.updatePrescription(emrMedOrders);
        return Result.success();
    }
}